package nettypro.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * @ClassName MyTextWebSocketFrameHandler
 * @Description TODO
 * @Author zeny
 * @Date 2020/3/25 0025 11:18
 */
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器端收到消息 " + msg.text());
        int count = 100;
        while (count-- > 0) {
            ctx.channel().writeAndFlush(new TextWebSocketFrame(LocalDateTime.now() + ", " + msg.text() + "\n"));
            Thread.sleep(1000);
        }
    }

    /**
     * @Description web客户端连接后出发
     * @Date 2020/3/25 0025 11:22
     * @param ctx
     * @return void
     **/
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务器 handlerAdded 被调用 " + ctx.channel().id().asLongText());
        System.out.println("服务器 handlerAdded 被调用 " + ctx.channel().id().asShortText());
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务器 handlerRemoved 被调用 " + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
